#include <stdio.h>
#include <string>
#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define NUM 1024
using namespace std;

//1.传文件描述符就行，不用传数组
//2.C/C++混编构建字符串常用接口：snprintf

void Writer(int wfd)
{
    char buffer[NUM];
    pid_t self = getpid();
    int number = 1;
    while(number--)
    {
        snprintf(buffer, sizeof(buffer), "%s","i am father");
        write(wfd, buffer, strlen(buffer));
        // char c = '1';
        // write(wfd, &c, sizeof(c));
        //cout << number++ << endl;
    }
      
}

void Reader(int rfd)        
{
    ssize_t n = 0;
    char buffer[NUM] = {0};
    while(true)
    {
        while(n = read(rfd,buffer,sizeof(buffer)))
        {
            buffer[n] = 0;
            cout << "child recieved :" << buffer << endl;
            break;
        }
    }
}

int main()
{
    int pipeArr[2] = {0};
    pipe(pipeArr);      //建立管道

    pid_t id = fork();
    if(id < 0)
    {
        perror("fork");
        exit(-1);
    }
    else if(id == 0)     //child 
    {
        close(pipeArr[1]);
        Reader(pipeArr[0]);
        close(pipeArr[0]);
        exit(0);
    }

    //father
    close(pipeArr[0]);
    Writer(pipeArr[1]);
    close(pipeArr[1]);

    int retid = 0;
    retid = waitpid(id, nullptr, 0);
    if(retid == -1)
    {
        perror("wait failed\n");
    }
    return 0;
}

